<template>
  <div class="student-wrapper">
    <div class="student-header-wrapper">
      <div class="student-header-search-wrapper">
        <el-input class="student-header-search-input"
                  prefix-icon="el-icon-search"
                  v-model="studentName"
                  placeholder="请输入学生名字进行搜索"></el-input>
        <el-button class="student-header-search-button"
                   icon="el-icon-search"
                   @click="getStudents"
                   type="primary">搜索</el-button>
      </div>
      <div class="student-header-operation-wrapper">
        <el-button class="student-header-add-button"
                   icon="el-icon-plus"
                   @click="showAddStudentDialog"
                   type="primary">添加学生</el-button>
        <el-button class="student-header-delete-batch-button"
                   icon="el-icon-delete"
                   @click="deleteStudentsByBatch"
                   :disabled="this.multipleSelections.length === 0"
                   type="danger">批量删除</el-button>
      </div>
    </div>
    <div class="student-table-wrapper">
      <el-table
              class="student-table"
              v-loading="loading"
              element-loading-text="拼命加载中"
              @selection-change="handleSelectionChange"
              :data="students"
              stripe>
        <el-table-column
                type="selection"
                width="55">
        </el-table-column>
        <el-table-column
                prop="name"
                label="姓名"
                fixed="left"
                width="90">
        </el-table-column>
        <el-table-column
                prop="schoolID"
                label="学号"
                width="120">
        </el-table-column>
        <el-table-column
                prop="gender"
                label="性别"
                width="65">
        </el-table-column>
        <el-table-column
                prop="department.name"
                label="学院"
                width="120">
        </el-table-column>
        <el-table-column
                prop="major.name"
                label="专业"
                width="140">
        </el-table-column>
        <el-table-column
                prop="classes.name"
                label="班级"
                width="70">
        </el-table-column>
        <el-table-column
                prop="dormitory"
                label="宿舍"
                width="110">
        </el-table-column>
        <el-table-column
                prop="phone"
                label="电话"
                width="120">
        </el-table-column>
        <el-table-column
                prop="email"
                label="邮箱"
                width="180">
        </el-table-column>
        <el-table-column label="操作"
                         fixed="right"
                         width="160">
          <template slot-scope="scope">
            <el-button size="mini"
                       @click="showEditStudentDialog(scope.row)"
                       type="primary">编辑</el-button>
            <el-button type="danger"
                       @click="deleteStudent(scope.row)"
                       size="mini">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="student-table-pagination-wrapper">
        <el-pagination
                background
                @current-change="currentChange"
                @size-change="sizeChange"
                layout="sizes, prev, pager, next, jumper, ->, total, slot"
                :total="total">
        </el-pagination>
      </div>
    </div>
    <el-dialog class="dialog"
               width="70%"
               :title="title"
               :visible.sync="dialogFormVisible">
      <div class="dialog-form-wrapper">
        <el-form class="dialog-form"
                 ref="studentForm"
                 :rules="rules"
                 :model="student" >
          <el-row :gutter="50">
            <el-col :span="8">
              <el-form-item label="姓名:" prop="name">
                <el-input v-model="student.name"
                          prefix-icon="el-icon-edit"
                          placeholder="请输入学生姓名"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="性别 : " prop="gender">
                <!--Radio 单选框-->
                <el-radio-group v-model="student.gender">
                  <el-radio-button label="男">男</el-radio-button>
                  <el-radio-button label="女">女</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="学号 : " prop="schoolID">
                <el-input v-model="student.schoolID"
                          disabled
                          prefix-icon="el-icon-edit"
                          placeholder="请输入学号"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="50">
            <el-col :span="8">
              <el-form-item label="学院 : " prop="departmentId">
                <el-select v-model="student.departmentId"
                           @change="onDepartmentChanged"
                           placeholder="请选择学院">
                  <el-option
                          v-for="item in departments"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="专业 : " prop="majorId">
                <el-select v-model="student.majorId"
                           @change="onMajorChanged"
                           placeholder="请选择专业">
                  <el-option
                          v-for="item in majorsByDepartmentId"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="班级 : " prop="classesId">
                <el-select v-model="student.classesId" placeholder="请选择班级">
                  <el-option
                          v-for="item in classesByMajorsId"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="50">
            <el-col :span="8">
              <el-form-item label="联系电话 : " prop="phone">
                <el-input v-model="student.phone"
                          prefix-icon="el-icon-mobile-phone"
                          placeholder="请输入联系电话"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系邮箱 : " prop="email">
                <el-input v-model="student.email"
                          prefix-icon="el-icon-message"
                          placeholder="请输入联系邮箱"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="宿舍地址 : " prop="dormitory">
                <el-input v-model="student.dormitory"
                          prefix-icon="el-icon-add-location"
                          placeholder="请输入宿舍地址"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogStudent">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: "EduStudents",
    data() {
      return {
        students: [],
        currentPage: 1,
        size: 10,
        studentName: '',
        total: 0,
        loading: false,
        dialogFormVisible: false,
        title: '',
        multipleSelections: [],
        departments: '',
        majors: '',
        majorsByDepartmentId: '',
        classes: '',
        classesByMajorsId: '',
        student: {
          id: null,
          name: '',
          gender: '',
          departmentId: null,
          majorId: null,
          classesId: null,
          phone: '',
          email: '',
          dormitory: '',
          schoolID: '',
          face: ''
        },
        rules: {
          name: [{ required: true, message: '请输入学生姓名', trigger: 'blur' }],
          gender: [{ required: true, message: '请输入学生性别', trigger: 'blur' }],
          departmentId: [{ required: true, message: '请选择学院', trigger: 'blur' }],
          majorId: [{ required: true, message: '请选择专业', trigger: 'blur' }],
          classesId: [{ required: true, message: '请输入班级', trigger: 'blur' }],
          phone: [{ required: true, message: '请输入电话', trigger: 'blur' }],
          email: [
            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
            { type:'email', required: true, message: '邮箱地址格式不正确', trigger: 'blur' },
          ],
          dormitory: [{ required: true, message: '请输入宿舍地址', trigger: 'blur' }]
        }
      }
    },
    mounted() {
      this.getStudents()
      this.getDepartments()
      this.getMajors()
      this.getClasses()
    },
    methods: {
      //  批量删除学生
      deleteStudentsByBatch() {
        this.$confirm('此操作将永久删除这['+ this.multipleSelections.length +']条同学的信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let ids = '?'
          this.multipleSelections.forEach(item => {
            ids += 'ids=' + item.id + '&'
          })
          this.deleteRequest('/edumanagement/student/' + ids).then(resp => {
            if (resp) {
              this.getStudents()
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      //  获取被选中的学生
      handleSelectionChange(data) {
        this.multipleSelections = data
      },
      //  添加或者更新学生
      dialogStudent() {
        if (this.student.id) {
          // 更新学生
          this.$refs['studentForm'].validate((valid) => {
            if (valid) {
              this.dialogFormVisible = false
              this.putRequest('/edumanagement/student/', this.student).then(resp => {
                if (resp) {
                  this.getStudents()
                }
              })
            }
          })
        } else {
          //  添加学生
          this.$refs['studentForm'].validate((valid) => {
            if (valid) {
              this.dialogFormVisible = false
              this.postRequest('/edumanagement/student/', this.student).then(resp => {
                if (resp) {
                  this.getStudents()
                }
              })
            }
          })
        }
      },
      //  删除学生
      deleteStudent(data) {
        //  MessageBox 弹框
        this.$confirm('此操作将永久删除[' + data.name + ']同学的信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteRequest('/edumanagement/student/' + data.id).then(resp => {
            if (resp) {
              this.getStudents()
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      //  获取学生列表
      getStudents() {
        this.loading = true
        this.getRequest('/edumanagement/student/?currentPage=' + this.currentPage
            + '&size=' + this.size
            + '&name=' + this.studentName).then(resp => {
          if (resp) {
            this.students = resp.data
            this.total = resp.total
          }
          this.loading = false
        })
      },
      //  当分页组件的每页显示多少条数据改变时
      sizeChange(size) {
        this.size = size
        this.currentPage = 1
        this.getStudents()
      },
      //  当分页组件的页数改变时
      currentChange(currentPage) {
        this.currentPage = currentPage
        this.getStudents()
      },
      //  展示添加的dialog
      showAddStudentDialog() {
        this.title = '添加学生'
        this.student = {
          id: null,
          name: '',
          gender: '',
          departmentId: null,
          majorId: null,
          classesId: null,
          phone: '',
          email: '',
          dormitory: '',
          schoolID: '',
          face: ''
        }
        this.getMaxSchoolID()
        this.dialogFormVisible = true
      },
      //  展示更新的dialog
      showEditStudentDialog(data) {
        this.title = '编辑学生信息'
        //  this.updatePos = data 这个直接赋值会导致bug，输入框与table里的数据同步变化
        //  Object.assign(target, source1, source2)方法用于对象的合并，将源对象（source）的所有可枚举属性，复制到目标对象（target)
        Object.assign(this.student, data)
        this.dialogFormVisible = true
      },
      //  当form里的学院改变时根据学院id改变专业列表的数据
      onDepartmentChanged() {
        this.student.majorId = null
        this.student.classesId = null
        let majors = []
        for (let i = 0; i < this.majors.length; i++) {
          if (this.student.departmentId === this.majors[i].departmentId) {
            majors.push(this.majors[i])
          }
        }
        this.majorsByDepartmentId = majors
      },
      //  当form里的专业改变时根据专业id改变班级列表的数据
      onMajorChanged() {
        this.student.classesId = null
        let classes = []
        for (let i = 0; i < this.classes.length; i++) {
          if (this.student.majorId === this.classes[i].majorId) {
            classes.push(this.classes[i])
          }
        }
        this.classesByMajorsId = classes
      },
      //  获取最大的学号
      getMaxSchoolID() {
        this.getRequest('/edumanagement/student/maxSchoolID').then(resp => {
          if (resp) {
            this.student.schoolID = resp
          }
        })
      },
      //  获取所有学院
      getDepartments() {
        this.getRequest('/edumanagement/student/department').then(resp => {
          if (resp) {
            this.departments = resp
          }
        })
      },
      //  获取所有专业
      getMajors() {
        this.getRequest('/edumanagement/student/major').then(resp => {
          if (resp) {
            this.majors = resp
            this.majorsByDepartmentId = resp
          }
        })
      },
      //  获取所有班级
      getClasses() {
        this.getRequest('/edumanagement/student/classes').then(resp => {
          if (resp) {
            this.classes = resp
            this.classesByMajorsId = resp
          }
        })
      }
    }
  }
</script>

<style lang="less">
  .student-wrapper {
    width: 90%;
    margin-top: 20px;
    margin-left: 40px;

    .student-header-wrapper {
      display: flex;
      justify-content: space-between;
      box-sizing: border-box;
      padding: 20px 20px;
      /*background-color: #EBEEF5;*/
      height: 80px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, .20), 0 0 6px rgba(0, 0, 0, .08);
      border-radius: 4px;

      .student-header-search-wrapper {


        .student-header-search-input {
          width: 220px;
          margin-right: 10px;
        }

        .student-header-search-button {
          height: min-content;
        }
      }

      .student-header-operation-wrapper {

        .student-header-add-button {

        }

        .student-header-delete-batch-button {

        }
      }
    }

    .student-table-wrapper {
      margin-top: 20px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, .20), 0 0 6px rgba(0, 0, 0, .08);
      border-radius: 4px;
      padding: 5px 20px 20px 20px;
      .student-table {
        width:100%;
      }

      .student-table-pagination-wrapper {
        margin-top: 20px;
        display: flex;
        justify-content: center;
      }
    }
  }

  .dialog {

    .dialog-form-wrapper {
      width: 90%;

      .dialog-form {

        .dialog-form-img-input {
          margin-bottom: 20px;
        }
      }
    }
  }
</style>